import { readFileSync, writeFileSync } from 'fs';
import { resolve } from 'path';
import { ITodoData } from '../src/typings.ts';

function readFile(path: string): string {
  return readFileSync(resolve(__dirname, path), 'utf8');
}

//data 暂时无法确定类型 将它用泛型定义 等writeFile方法被执行时才传类型T 过去
function writeFile<T>(path: string, data: T): void {
  return writeFileSync(resolve(__dirname, path), JSON.stringify(data));
}

//操作文件
function fileOperation(path: string, fn?: any): string | void {
  let todoList: ITodoData[] = JSON.parse(readFile(path) || '[]');

  if (!fn) {
    return JSON.stringify(todoList);
  }

  //删除某一项
  todoList = fn(todoList);

  writeFile<ITodoData[]>(path, todoList);
}

export { readFile, writeFile, fileOperation };
